package com.hk.core.autoconfigure.exception.servlet;

import com.hk.commons.JsonResult;
import com.hk.commons.Status;
import com.hk.commons.util.SpringContextHolder;
import jakarta.persistence.EntityNotFoundException;
import jakarta.persistence.PersistenceException;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * jpa 异常处理器
 *
 * @author Kevin
 * @date 2018-10-22 22:22
 */
@RestControllerAdvice
public class JpaExceptionHandler extends AbstractExceptionHandler {

    /**
     * <p>
     * getOne(String id) 无此记录时，将抛出 EntityNotFoundException.<br/>
     * 响应状态码： 404
     * </p>
     *
     * @param e e
     * @return {@link JsonResult}
     */
    @ExceptionHandler(value = {EntityNotFoundException.class})
    @ResponseStatus(HttpStatus.OK)
    public JsonResult<Void> entityNotFoundException(EntityNotFoundException e, HttpServletRequest request) {
        error(e, e.getMessage(), request);
        return new JsonResult<>(Status.NOT_FOUND, SpringContextHolder.getMessage("access.resource.not.found.message"));
    }

    @ExceptionHandler(value = {PersistenceException.class})
    @ResponseStatus(HttpStatus.OK)
    public JsonResult<Void> persistenceException(PersistenceException e, HttpServletRequest request) {
        error(e, e.getMessage(), request);
        return new JsonResult<>(Status.NOT_FOUND, SpringContextHolder.getMessage("operation.failure"));
    }
}
